import 'dart:io';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';

import 'hero.dart';

class SimplePicsWiper extends StatefulWidget {
  const SimplePicsWiper({super.key, required this.url, required this.images});
  final String url;
  final List<String> images;

  @override
  _SimplePicsWiperState createState() => _SimplePicsWiperState();
}

class _SimplePicsWiperState extends State<SimplePicsWiper> {
  final GlobalKey<ExtendedImageSlidePageState> slidePagekey = GlobalKey<ExtendedImageSlidePageState>();
  final List<int> _cachedIndexes = <int>[];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final int index = widget.images.indexOf(widget.url);
    _preloadImage(index - 1);
    _preloadImage(index + 1);
  }

  void _preloadImage(int index) {
    if (_cachedIndexes.contains(index)) return;
    if (0 <= index && index < widget.images.length) {
      final String url = widget.images[index];
      if (url.startsWith('https:')) {
        precacheImage(ExtendedNetworkImageProvider(url, cache: true), context);
      }
      _cachedIndexes.add(index);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: ExtendedImageSlidePage(
        key: slidePagekey,
        slideAxis: SlideAxis.both,
        slideType: SlideType.wholePage,
        child: GestureDetector(
          onTap: () {
            slidePagekey.currentState!.popPage();
            Navigator.pop(context);
          },
          child: ExtendedImageGesturePageView.builder(
            controller: ExtendedPageController(
              initialPage: widget.images.indexOf(widget.url),
              pageSpacing: 50,
              shouldIgnorePointerWhenScrolling: false,
            ),
            itemCount: widget.images.length,
            onPageChanged: (int page) {
              _preloadImage(page - 1);
              _preloadImage(page + 1);
            },
            itemBuilder: (BuildContext context, int index) {
              final String url = widget.images[index];
              return url == 'This is an video'
                  ? ExtendedImageSlidePageHandler(
                child: Material(
                  child: Container(
                    alignment: Alignment.center,
                    color: Colors.yellow,
                    child: const Text('This is an video'),
                  ),
                ),
                heroBuilderForSlidingPage: (Widget result) {
                  return Hero(
                    tag: url,
                    child: result,
                    flightShuttleBuilder: (BuildContext flightContext,
                        Animation<double> animation,
                        HeroFlightDirection flightDirection,
                        BuildContext fromHeroContext,
                        BuildContext toHeroContext) {
                      final Hero hero =
                      (flightDirection == HeroFlightDirection.pop
                          ? fromHeroContext.widget
                          : toHeroContext.widget) as Hero;
                      return hero.child;
                    },
                  );
                },
              )
                  : HeroWidget(
                tag: url,
                slideType: SlideType.wholePage,
                slidePagekey: slidePagekey,
                child: url.startsWith("http")
                    ? ExtendedImage.network(
                  url,
                  enableSlideOutPage: true,
                  fit: BoxFit.contain,
                  mode: ExtendedImageMode.gesture,
                  initGestureConfigHandler: (ExtendedImageState state) {
                    return GestureConfig(
                      inPageView: true,
                      initialScale: 1.0,
                      maxScale: 5.0,
                      animationMaxScale: 6.0,
                      initialAlignment: InitialAlignment.center,
                    );
                  },
                  loadStateChanged: (ExtendedImageState state) {
                    switch (state.extendedImageLoadState) {
                      case LoadState.failed:
                        return const Center(child: Text('加载失败'));
                      default:
                        return null;
                    }
                  },
                )
                    : ExtendedImage.file(
                  File(url),
                  enableSlideOutPage: true,
                  fit: BoxFit.contain,
                  mode: ExtendedImageMode.gesture,
                  initGestureConfigHandler: (ExtendedImageState state) {
                    return GestureConfig(
                      inPageView: true,
                      initialScale: 1.0,
                      maxScale: 5.0,
                      animationMaxScale: 6.0,
                      initialAlignment: InitialAlignment.center,
                    );
                  },
                  loadStateChanged: (ExtendedImageState state) {
                    switch (state.extendedImageLoadState) {
                      case LoadState.failed:
                        return const Center(child: Text('加载失败'));
                      default:
                        return null;
                    }
                  },
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}
